﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace Sofire.Data.XSql
{
    internal class XSqlTextNode : XSqlNodeBase, IXSqlTextNode
    {
        private readonly static Regex BindRegex = new Regex("#{[^}]+}", RegexOptions.Compiled);

        private string _Text;
        public string Text
        {
            get
            {
                return this._Text;
            }
            set
            {
                this._Text = value;
                this._textMatches = null;
            }
        }

        public override XSqlType Type
        {
            get { return XSqlType.Text; }
        }

        public override XObject CreateXObject()
        {
            var test = this._Text;
            if(test != null)
            {
                if(test.IndexOfAny(XmlEscapes) > -1)
                {
                    return new XCData(this._Text);
                }
                else
                {
                    return new XText(this._Text);
                }
            }
            return new XText(string.Empty);
        }

        protected override void Load(XmlNode node)
        {
            this._Text = node.InnerText;
            this._textMatches = BindRegex.Matches(this._Text);
            if(this._textMatches.Count > 0)
            {
                this._bindList = new List<XSqlBindItem>(this._textMatches.Count);
            }
            else
            {
                this._onceCompiled = true;
            }
        }

        private bool _onceCompiled = false;
        private MatchCollection _textMatches;

        private List<XSqlBindItem> _bindList;
        private List<string> _nonBindList;

        private string _compiledText;

        private string CompileText(XSqlParameterCollection parameters)
        {
            StringBuilder builder = new StringBuilder();
            Match lastMatch = null;
            foreach(Match match in this._textMatches)
            {
                if(lastMatch == null)
                {
                    //- 添加第一个匹配的前的所有文本
                    builder.Append(this._Text.Substring(0, match.Index));
                }
                else
                {
                    var nextIndex = lastMatch.Index + lastMatch.Length;
                    builder.Append(this._Text.Substring(nextIndex, match.Index - nextIndex));
                }

                XSqlBindItem item = parameters.CreateBindItem(match.Value);
                if(item.IsBind)
                {
                    builder.Append(this.Document.Engine.ParameterPrefixWithText);
                    builder.Append(item.Name);
                    this._bindList.Add(item);
                }
                else
                {
                    if(this._nonBindList == null) this._nonBindList = new List<string>();

                    builder.Append("{");
                    builder.Append(this._nonBindList.Count);
                    builder.Append("}");
                    this._nonBindList.Add(item.Name);
                }
                lastMatch = match;
            }
            if(lastMatch != null)
            {
                var nextIndex = lastMatch.Index + lastMatch.Length;
                builder.Append(this._Text.Substring(nextIndex));
            }
            return builder.ToString();
        }

        private void ConvertBindValues(XSqlParameterCollection parameters)
        {
            //- 转换参数值
            if(this._bindList != null)
            {
                foreach(var item in this._bindList)
                {
                    item.ConvertParameter(parameters);
                }
            }
        }

        private string CompileText(bool cache, XSqlParameterCollection parameters)
        {
            #region Cache Complied Text

            if(cache)
            {
                if(this._compiledText != null) goto END;
                lock(this)
                {
                    if(this._compiledText != null) goto END;
                }
            }
            lock(this)
            {
                this._compiledText = this.CompileText(parameters);
            }
            #endregion

        END:
            this.ConvertBindValues(parameters);

            if(this._nonBindList == null) return this._compiledText;

            //- 格式化非绑定的参数
            object[] formatArgs = new object[this._nonBindList.Count];
            for(int i = 0 ; i < this._nonBindList.Count ; i++)
            {
                formatArgs[i] = parameters.GetValue(this._nonBindList[i]);
            }

            return string.Format(this._compiledText, formatArgs);
        }

        public override string Compile(XSqlParameterCollection parameters)
        {
            //- 文本内不包含 #{} 参数绑定
            if(this._onceCompiled) return this._Text;

            //- foreach 动态绑定模式。理论上，每一次循环的文本必然不同，所不进行缓存
            return this.CompileText(!parameters.IsDynamicBind, parameters);
        }
    }
}
